import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Modal,
} from 'antd';

import echarts from 'echarts/lib/echarts';
import "echarts/lib/chart/graph";

import DataSet from "@antv/data-set";
import {getReadableSize} from '@/utils/dsrsUtil';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '../search.less';
const FormItem = Form.Item;
const formLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
/* eslint react/no-multi-comp:0 */
@connect(({ fileSource, loading }) => ({
  fileSource,
  loading: loading.models.fileSource,
}))
@Form.create()
class FileSource extends PureComponent {
  state = {
    expandForm: false,
    selectedRows: [],
    detailVisible: false,
    gjData: {},
    text: {},
  };

  columns = [
    {
      title: '文件名称',
      dataIndex: 'fileName',
    },
    {
      title: '操作人',
      dataIndex: 'optName',
    },
    {
      title: '大小',
      dataIndex: 'fileSize',
      render: (text, record) => {
        if (text) {
          return getReadableSize(text * 1024);
        } else {
          return '--'
        }
      },
    },
    {
      title: '密级',
      dataIndex: 'secretLevelName',
    },

    {
      title: '初始来源',
      dataIndex: 'fileSourceName',
    },
    {
      title: '操作',
      render: (text, record) => (
        <a onClick={() => this.detailHandelVisible(true,text)}>查看轨迹</a>
      ),
    },
  ];

  componentDidMount() {
    this.pageList();
  }

  // 分页查询列表
  pageList(data,pageSize=10,pageNum=0) {
    const { dispatch } = this.props;
    const values = {
      fileName: data && data.fileName || '',
      secretLevel: data && data.secretLevel || '',
      fileSourceName: data && data.fileSourceName || '',
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'fileSource/queryList',
      payload: values,
    });
  }

  // 文件轨迹
  queryGj(data) {
    const { dispatch } = this.props;
    const values = {
      fileId: data && data.fileId || null,
      type: data && data.type,
    }
    dispatch({
      type: 'fileSource/getGj',
      payload: values,
      callback: (res) => {
      if(res.result == "ok") {
        this.setState({
          gjData: res.data
        })
      }else {
        Modal.error({
          title: '操作失败',
          content: res.msg,
        });
      }
    },
    });
  }

  handleStandardTableChange = (pagination, filters, sorter) => {
    // 分页请求
    this.pageList({},pagination.pageSize,pagination.current-1);
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  detailHandelVisible = (flag,text) => {
    this.setState({
      detailVisible: !!flag,
      text
    });
    if (flag) {
      const data = {
        fileId: text.id,
        type: text.fileSource
      }
      this.queryGj(data)
    }
  };

  //查询
  handleSearch = e => {
    e.preventDefault();
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
     /* this.setState({
        formValues: fieldsValue,
      })*/
      const params = {
        fileName: fieldsValue.fileName || '',
        secretLevel: fieldsValue.secretLevel || '',
        fileSourceName: fieldsValue.fileSourceName || '',
      }
      this.pageList(params);
     /* this.pageList(fieldsValue);*/
    });
  };

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={7} sm={24}>
            <FormItem label="文件名称">
              {getFieldDecorator('fileName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

          <Col md={7} sm={24}>
            <FormItem label="密级">
              {getFieldDecorator('secretLevel')(
                <Select placeholder="全部">
                  <Option value="">全部</Option>
                  <Option value="1">非密</Option>
                  <Option value="2">普通</Option>
                  <Option value="3">秘密</Option>
                  <Option value="4">机密</Option>
                  <Option value="5">绝密</Option>
                </Select>
              )}
            </FormItem>
          </Col>

          {/*<Col md={7} sm={24}>*/}
            {/*<FormItem label="初始来源">*/}
              {/*{getFieldDecorator('fileSourceName')(*/}
                {/*<Select placeholder="全部">*/}
                  {/*<Option value="全部">全部</Option>*/}
                  {/*<Option value="本地上传">本地上传</Option>*/}
                  {/*<Option value="数据采集平台">数据采集平台</Option>*/}
                  {/*<Option value="清单报表系统">清单报表系统</Option>*/}
                  {/*<Option value="堡垒机目录">堡垒机目录</Option>*/}
                  {/*<Option value="业务运维取数目录">业务运维取数目录</Option>*/}
                {/*</Select>*/}
              {/*)}*/}
            {/*</FormItem>*/}
          {/*</Col>*/}

          <Col md={3} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      fileSource: { data },
      loading,
    } = this.props;
    const { selectedRows,detailVisible, gjData, text} = this.state;
    const detailsMethods = {
      detailHandelVisible: this.detailHandelVisible,
    };
    return (
      <PageHeaderWrapper title="文件追溯">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <TableList
              className={styles.tdPadding}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              hideRowSelection={true}
              onChange={this.handleStandardTableChange.bind(this)}
              rowKey={record => record.id}
            />
            {detailVisible?(
              <Details {...detailsMethods} detailVisible={detailVisible} gjData={gjData} text={text} />
            ):null}
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
class Details extends PureComponent {
  componentDidMount(){
    let that = this;
    //
    setTimeout(function(){

      const { gjData } = that.props;
      let categories = ['外发','流转','共享','下载','上传','预览'];

      let optionsP = {
        title: {
            text: 'Les Miserables',
            subtext: 'Default layout',
            top: 'bottom',
            left: 'right'
        },
        tooltip: {},
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        label: {
          normal: {
              show: true,
              textStyle: {
                  fontSize: 12
              },
          }
        },
        legend: {
          x: "center",
          show: true,
          data: categories
        },
        series: [
          {
            type: 'graph',
            layout: 'force',
            symbolSize: 45,
            focusNodeAdjacency: true,
            roam: true,
            categories: categories,
            label: {
              normal: {
                show: true,
                textStyle: {
                    fontSize: 12
                },
              }
            },
            force: {
              repulsion: 1000
            },
            edgeSymbolSize: [4, 50],
            edgeLabel: {
              normal: {
                show: true,
                textStyle: {
                    fontSize: 10
                },
                formatter: "{c}"
              }
            },
            data: [],
            links: [],
            lineStyle: {
              normal: {
                opacity: 0.9,
                width: 1,
                curveness: 0
              }
            }
          }
        ]
      }
      if (gjData&&gjData.data) {
        optionsP.series[0].data = gjData.data;
        optionsP.series[0].links = gjData.links;
      }
      let myChart = echarts.init(document.getElementById('main'));
      myChart.setOption(optionsP);
       //一些事件
      myChart.on('click', params=> {
          console.log(params);
      });

    },500)

  }
  render() {
    const { detailVisible, detailHandelVisible, gjData, text } = this.props;
    let data = gjData;
    var dv = new DataSet.View().source(data, {
      type: "hierarchy",
      pureData: true
    });
    dv.transform({
      type: "hierarchy.compact-box",
      direction: "TB",

      getHGap() {
        return 28
      },

      getVGap() {
        return 28;
      },

      getHeight() {
        return 28;
      },

      getWidth(d) {
        return 28 * (d && d.userName && d.userName.length);
      }
    });
    return (
      <Modal
        destroyOnClose
        width={1200}
        title="查看轨迹"
        visible={detailVisible}
        onOk={() => detailHandelVisible()}
        onCancel={() => detailHandelVisible()}
        footer={[
          <Button key="back" type="primary" onClick={() => detailHandelVisible()}>返回</Button>
        ]}
        className={styles.viewMore}
      >
         <div>
         <Row style={{borderBottom:'1px solid #e8e8e8'}}>
          <Col md={12}>
            <FormItem {...formLayout} label="文件名称">
              {text.fileName}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="大小">
              {text.fileSize?getReadableSize(text.fileSize * 1024):'--'}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="密级">
              {text.secretLevelName}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="初始来源">
              {text.fileSourceName}
            </FormItem>
          </Col>
        </Row>
         <div id="main" style={{height:'500px'}}></div>
      </div>
      </Modal>
    );
  }
}
export default FileSource;
